/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.testis.utils.tree;

import java.util.LinkedList;

import org.testis.utils.tree.TreeNode;

/**
 *
 * @author emir
 */
public class TreeNode {
    private String m_name;
    private Object m_object;
    private TreeNode m_parent;
    private LinkedList<TreeNode> m_children;


    public String getName()
    {
        return m_name;
    }


    public void setName(String name)
    {
        this.m_name = name;
    }


    public Object getObject()
    {
        return m_object;
    }


    public void setObject(Object object)
    {
        this.m_object = object;
    }


    public TreeNode getParent()
    {
        return m_parent;
    }


    public void setParent(TreeNode parent)
    {
        this.m_parent = parent;
    }


    public TreeNode[] getChildren()
    {
        return (TreeNode[])m_children.toArray();
    }
    
    public TreeNode searchChild(Object child) {
        if (this.getObject()==child) {
            return this;
        } else {
            int i;
            TreeNode node=null;
            for (i=0;i<m_children.size();i++) {
                node=searchChild(m_children.get(i));
                if (node!=null) {
                    return node;
                }
            }
            return null;
        }
    }


    public void setChildren(TreeNode[] children)
    {
        deleteAllChildren();
        for (int i=0;i<children.length;i++) {
            addChild(children[i]);
        }
    }
    
    public void addChild(TreeNode node) {
        if(node==null||m_children.contains(node))
            return;
        this.m_children.add(node);
        node.setParent(this);
    }
    
    public void deleteChild(TreeNode node) {
          if(node==null)
            return;
        this.m_children.remove(node);
        node.setParent(null);
    }
    
    public void deleteAllChildren() {
        while (this.m_children.size()>0)
        {
            this.m_children.removeFirst().setParent(null);
        }
    }
    
    public void purgeAllChildren() {
        TreeNode node;
        while (this.m_children.size()>0)
        {
            node = this.m_children.removeFirst();
            node.setParent(null);
            node.purgeAllChildren();
        }
    }
    public String toString() {
        if (getObject()!=null) {
            return getObject().toString();
        } else {
            return getName();
        }
    }
    
    public boolean hasChildren()
    {
        if(m_children.size() > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}